package com.shujia.day17;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Code04GetField {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {

        Class<?> aClass = Class.forName("com.shujia.day17.Student");

        /*
            需求：单独获取类中的成员变量

            getField
                通过类对象获取指定名称的成员变量 将其包装成一个Field类型的对象

            set
                第一个参数是学生的对象  第二个参数是成员变量的值
         */

        Field name = aClass.getField("name");
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance();
        System.out.println(o);
        name.set(o,"张从文");
        System.out.println(o);


        Field age = aClass.getDeclaredField("age");

        // Class com.shujia.day17.Code04GetField can not access a member of
        //      class com.shujia.day17.Student with modifiers "private
        age.setAccessible(true);
        age.set(o,23);
        System.out.println(o);


    }
}
